import config from "../config.js";
import {
	getImageInfo
} from './wx'


const whiteList = ['wx_paas_app_path']

let isInit = false;

function login(options = {}) {
	return new Promise((resolve, reject) => {
		wx.login({
			...options,
			success(res) {
				if (res.code) {
					resolve(res.code);
				} else {
					reject("登录失败！" + res.errMsg);
				}
			},
			fail(res) {
				reject("登录失败！" + res.errMsg);
			},
		});
	});
}

function request(url, options = {}) {
	return new Promise((resolve, reject) => {
		wx.request({
			url,
			...options,
			success(res) {
				resolve(res);
			},
			fail(res) {
				reject(res.errMsg);
			},
		});
	});
}

const promiseReq = {}

async function execPost(_name, payload = {}, options = {}) {
	try {
		if (!promiseReq['checkToken']) {
			promiseReq['checkToken'] = checkToken()
		}
		await promiseReq['checkToken']
		delete promiseReq['checkToken']
		const token = wx.getStorageSync("token");
		const {
			data
		} = await request(
			`${config.BASE_URL}/action/apimanager/exec?token=${token}&account_no=${config.PASS.account_no}`, {
				data: {
					_name,
					...payload,
				},
				method: "POST",
				...options,
			}
		);
		if (!data.success && data.message && data.message != '请先登录') {
			wx.showToast({
				title: data.message,
				icon: 'none',
				duration: 3000
			})
			throw new Error(data.message)
		}
		return data;
	} catch (e) {
		throw new Error(e);
	}
}

let interId = null;
async function getToken() {
	try {
		const code = await login()
		const {
			data
		} = await request(
			`${config.BASE_URL}/action/weixin/wxmalogin`, {
				data: {
					code,
					...config.PASS,
				},
				method: "POST",
			}
		);
		wx.setStorageSync("token", data.token);
		wx.setStorageSync("ep", data.ep);
		wx.setStorageSync("openid", data.openid);
		wx.setStorageSync("unionid", data.unionid);
		await checkToken();
		if (!interId) {
			interId = setInterval(checkToken, 60000);
		}
		return data;
	} catch (e) {
		throw new Error(e);
	}
}

async function refreshToken() {
	try {
		const {
			data
		} = await request(
			`${config.BASE_URL}/action/apimanager/refreshtoken`, {
				method: "GET",
			}
		);
		return data;
	} catch (e) {
		throw new Error(e);
	}
}

async function checkToken() {
	try {
		const token = wx.getStorageSync("token");
		const ep = +(wx.getStorageSync("ep") ?? 0);
		if (token && ep) {
			const now = Date.now();
			if (ep < now) {
				await getToken();
			} else if (ep < now + 600000) {
				const data = await refreshToken();
				wx.setStorageSync("token", data.token);
				wx.setStorageSync("ep", data.ep);
			}
		} else {
			await getToken();
		}
	} catch (e) {
		throw new Error(e);
	}
}


/* 
  formData: {
	  filetype,
	  name: "file"
  }
 */

// 上传文件
async function uploadFile(filePath, size = 0, formData, options = {}) {
	wx.showLoading({
		title: '上传中'
	})
	if (formData.filetype == 'image') {
		const matchArr = filePath.match(/^https?:\/\/[^\s/?#]+\/[^\s?#]*\.(jpe?g|png|webp|gif|svg)(?:[\?#]|$)/i)
		if (matchArr && matchArr[1]) {
			// formData.filetype = `image/${matchArr[1]}`
			formData.filetype = `${matchArr[1]}`
		}
	}
	return new Promise((resolve, reject) => {
		wx.uploadFile({
			url: `${config.BASE_URL}/action/fileapi/fileupload?size=${size}`,
			filePath,
			name: 'file',
			formData,
			success(res) {
				wx.hideLoading()
				resolve(JSON.parse(res.data))
			},
			fail(err) {
				wx.hideLoading()
				reject(err)
			},
			...options
		})
	})
}

// 压缩图片
export async function compressImageByCanvas(canvasId, src, maxWidth, maxHeight, quality) {
	const image = await getImageInfo({
		src
	})
	let ratio = Math.min(maxWidth / image.width, maxHeight / image.height);
	let canvasWidth = image.width * ratio;
	let canvasHeight = image.height * ratio;

	const ctx = wx.createCanvasContext(canvasId);
	ctx.drawImage(src, 0, 0, canvasWidth, canvasHeight);
	return new Promise((resolve, reject) => {
		wx.canvasToTempFilePath({
			canvasId,
			fileType: image.type,
			quality: quality,
			success: async function(res) {
				const image = await getImageInfo({
					src: res.tempFilePath
				})
				resolve(image); // 返回压缩后的图片临时路径
			},
			fail: function(err) {
				reject(err);
			}
		});
	})
}


export {
	login,
	request,
	execPost,
	getToken,
	refreshToken,
	checkToken,
	uploadFile
};